package com.ctf.soft.ms.utils;

import com.alibaba.fastjson.JSON;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author lizhan
 */
public class HttpUtil {

    public static String getHttp(String url) {
        return loadHttp(url, "GET", null);
    }

    public static String postHttp(String url, String postData) {
        byte[] bData = null;
        try {
            bData = postData.getBytes("utf-8");
        } catch (Exception e) {
            // TODO: handle exception
        }
        return loadHttp(url, "POST", bData);
    }

    public static String getHttps(String url) {
        return loadHttps(url, "GET", "", "");
    }

    public static String postHttps(String url, String postData) {
        return loadHttps(url, "POST", postData, "");
    }

    public static String loadHttps(String requestUrl, String requestMethod, String postData, String cookie) {
        byte[] bData = null;
        if (postData != null && !postData.equals("")) {
            try {
                bData = postData.getBytes("utf-8");
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
        return loadHttps(requestUrl, requestMethod, bData, cookie);
    }

    public static String loadHttps(String requestUrl, String requestMethod, byte[] data, String cookie) {
        String result = "";
        try {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            URL url = new URL(requestUrl);
            HttpsURLConnection httpsURLConn = (HttpsURLConnection) url.openConnection(); // 获取连接
            httpsURLConn.setSSLSocketFactory(ssf);
            httpsURLConn.setDoInput(true);
            httpsURLConn.setDoOutput(true);
            httpsURLConn.setUseCaches(false);
            httpsURLConn.setRequestMethod(requestMethod); // 设置请求方法POST或GET
            httpsURLConn.setRequestProperty("Cookie", cookie);
            httpsURLConn.setConnectTimeout(5 * 1000); // 五秒超时
            httpsURLConn.setReadTimeout(10 * 1000);
            if ("GET".equalsIgnoreCase(requestMethod)) {
                httpsURLConn.connect();
            }
            if (null != data) {
                OutputStream outputStream = httpsURLConn.getOutputStream();
                outputStream.write(data);
                outputStream.close();
            }
            InputStream is = httpsURLConn.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "UTF-8");
            BufferedReader br = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            String str;
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            br.close();
            isr.close();
            is.close();
            httpsURLConn.disconnect();
            result = sb.toString();
            System.out.println("content:-->" + result);
        } catch (ConnectException ce) {
            // LogUtil.logInfo("Weixin server connection timed out.");
        } catch (IOException ioe) {
            try {
                throw new Exception("接口调用失败");
            } catch (Exception e) {
                // LogUtil.logInfo("https request error:{}" + e.getMessage());
            }
        } catch (KeyManagementException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

    public static String uploadFile(String url, String formName, String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            return uploadFile(url, formName, file);
        } else {
            return "";
        }
    }

    public static String uploadFile(String url, String formName, File file) {
        String responseContent = "";
        HttpURLConnection url_con = null;
        try {
            String BOUNDARY = "----------" + System.currentTimeMillis();
            url_con = (HttpURLConnection) new URL(url).openConnection();
            url_con.setRequestMethod("POST"); // 以Post方式提交表单，默认get方式
            url_con.setDoInput(true);
            url_con.setDoOutput(true);
            url_con.setUseCaches(false); // post方式不能使用缓存
            // 设置请求头信息
            url_con.setRequestProperty("Connection", "Keep-Alive");
            url_con.setRequestProperty("Charset", "utf-8");
            // 设置边界
            url_con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
            // 请求正文信息
            // 第一部分：
            StringBuilder sb = new StringBuilder();
            sb.append("--"); // 必须多两道线
            sb.append(BOUNDARY);
            sb.append("\r\n");
            sb.append("Content-Disposition: form-data;name=\"" + formName + "\";filename=\"" + file.getName() + "\"\r\n");
            sb.append("Content-Type:application/octet-stream\r\n\r\n");
            byte[] head = sb.toString().getBytes("utf-8");
            OutputStream out = new DataOutputStream(url_con.getOutputStream());
            out.write(head);
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            int bytes;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            in.close();
            byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
            out.write(foot);
            out.flush();
            out.close();
            InputStream iddn = url_con.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(iddn, "utf-8"));
            String tempLine = rd.readLine();
            StringBuffer tempStr = new StringBuffer();
            String crlf = System.getProperty("line.separator");
            while (tempLine != null) {
                tempStr.append(tempLine);
                tempStr.append(crlf);
                tempLine = rd.readLine();
            }
            responseContent = tempStr.toString();
            rd.close();
        } catch (IOException e) {
            // logger.error("网络故障", e);
        } finally {
            if (url_con != null) {
                url_con.disconnect();
            }
        }
        return responseContent;
    }

    public static File downloadFile(String url, String folderPath) {
        return downloadFile(url, folderPath, new Date().getTime() + ".txt");
    }

    public static File downloadFile(String url, String folderPath, String fileName) {
        byte[] buf = new byte[10240];
        int size;
        folderPath += folderPath.endsWith("\\") ? "" : "\\";
        String filePath = folderPath + fileName;
        try {
            //建立链接
            HttpURLConnection httpConnection = (HttpURLConnection) new URL(url).openConnection();
            httpConnection.connect();
            Map<String, List<String>> headMap = httpConnection.getHeaderFields();
            System.out.println(JSON.toJSONString(headMap));
            if (headMap.containsKey("Content-disposition")) {
                List<String> list = headMap.get("Content-disposition");
                Pattern pattern = Pattern.compile("(?<=filename=\")(.+)(?=\")");
                Matcher matcher;
                for (int i = 0; i < list.size(); ) {
                    matcher = pattern.matcher(list.get(i));
                    if (matcher.find()) {
                        fileName = matcher.group();
                        filePath = folderPath + fileName;
                        i = list.size();
                    } else {
                        i++;
                    }
                }
            }
            BufferedInputStream bis = new BufferedInputStream(httpConnection.getInputStream());
            //建立文件
            File file = new File(filePath);
            if (!file.exists()) {
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                file.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(filePath);
            //保存文件
            while ((size = bis.read(buf)) != -1) {
                fos.write(buf, 0, size);
            }
            fos.close();
            bis.close();
            httpConnection.disconnect();
            return file.length() > 0 ? file : null;
        } catch (IOException e) {

        }
        return null;
    }

    public static String loadHttp(String requestUrl, String requestMethod, byte[] postDate) {
        StringBuffer buffer = new StringBuffer();
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod.equalsIgnoreCase("POST") ? "POST" : "GET");
            if ("GET".equals(requestMethod))
                httpUrlConn.connect();
            // 当有数据需要提交时
            if (null != postDate) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(postDate);
                outputStream.close();
            }
            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            httpUrlConn.disconnect();
        } catch (ConnectException ce) {
        } catch (Exception e) {
        }
        return buffer.toString();
    }
}
